package com.xforceplus.bsstool.db;

import com.xforceplus.bsstool.config.ConfigMain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 老运营BSS数据库连接
 */
public class OldBssDB {
  private static final Logger logger = LoggerFactory.getLogger(OldBssDB.class);
  private static Connection conn = null;

  public static void releaseConnection(){
    if (conn!=null) {
      try {
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
      conn=null;
    }
  }


  public static List<Map> getSqlResult(String sql,Object... objects) throws Exception {
    Connection conn = null;
    PreparedStatement preparedStatement = null;
    ResultSet rs = null;
    try {
      if (conn == null) {
        Class.forName("com.mysql.jdbc.Driver");
        // 设置SSH本地端口转发后，访问本地ip+port就可以访问到远程的ip+port
        conn = DriverManager.getConnection(ConfigMain.OLD_BSS_DB_URL, ConfigMain.OLD_BSS_DB_USER_NAME, ConfigMain.OLD_BSS_DB_PASSWORD);
      }
      preparedStatement = conn.prepareStatement(sql);
      //设置参数
      if (objects != null && objects.length > 0) {
        for (int i = 0; i < objects.length; i++) {
          preparedStatement.setObject(i + 1, objects[i]);
        }
      }

      rs = preparedStatement.executeQuery();
      List<Map> resultList = new ArrayList<>();
      while (rs.next()) {
        Map resultMap = new HashMap();
        ResultSetMetaData resultSetMetaData = rs.getMetaData();
        int columnCount = resultSetMetaData.getColumnCount();
        for (int i=1; i<=columnCount; i++) {
          resultMap.put(resultSetMetaData.getColumnLabel(i), rs.getObject(i));
        }
        resultList.add(resultMap);
      }
      return resultList;
    } catch (Exception e) {
      logger.error("获取老运营BSS数据信息异常",e);
      throw e;
    } finally {
      if (rs!=null) {rs.close();rs=null;}
      if (preparedStatement!=null) {
        preparedStatement.close();
        preparedStatement=null;
      }
      if (conn!=null) {
        conn.close();
        conn=null;
      }
    }
  }



  public static void main(String[] args) throws Exception {
    List<Map> resultList = getSqlResult("select * from bss_group where group_code = 'HRWJ' ");
    System.out.println("resultList:"+resultList);
  }

}
